package com.homedo.microservice.distributed.id.service.remote.api.impl;

import com.homedo.microservice.distributed.id.service.api.IGenerateNoServiceRemote;
import com.homedo.microservice.distributed.id.service.exception.LeafServerException;
import com.homedo.microservice.distributed.id.service.exception.NoKeyException;
import com.homedo.microservice.distributed.id.service.service.SnowflakeService;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GenerateNoServiceRemoteImpl implements IGenerateNoServiceRemote {

    @Autowired
    private SnowflakeService snowflakeService;

    @Override
    public String generateNo(@PathVariable("key") String key) {
        return get(key, snowflakeService.getId(key));
    }

    private String get(String key, Result id) {
        Result result;
        if (key == null || key.isEmpty()) {
            throw new NoKeyException();
        }

        result = id;
        if (result.getStatus().equals(Status.EXCEPTION)) {
            throw new LeafServerException(result.toString());
        }
        return String.valueOf(result.getId());
    }
}
